import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_wan_android/arch/net/http_manager.dart';
import 'package:flutter_wan_android/arch/net/result_data.dart';
import 'package:flutter_wan_android/arch/ui/toast.dart';
import 'package:flutter_wan_android/model/article.dart';
import 'package:flutter_wan_android/res/colors.dart';
import 'package:flutter_wan_android/res/theme.dart';
import 'package:flutter_wan_android/widget/article_item.dart';
import 'package:flutter_wan_android/widget/empty_list.dart';
import 'package:flutter_wan_android/widget/refresh.dart';
import 'package:flutter_wan_android/widget/wan_appbar.dart';
import 'package:fluttertoast/fluttertoast.dart';

class Search extends StatefulWidget {
  @override
  _SearchState createState() => _SearchState();
}

class _SearchState extends State<Search> {
  List<Article> _articles = [];

  EasyRefreshController _controller = EasyRefreshController();

  var _pageIndex = 0;

  var keyWords = "";

  TextEditingController _etController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _titleBar(context),
      body: Container(
        color: wTheme.background,
        child: _contentPage(),
      ),
    );
  }

  /// 顶部搜索栏
  _titleBar(BuildContext context) {
    return WanAppbar(context,
        title: ClipRRect(
          borderRadius: BorderRadius.circular(15),
          child: Container(
            color: Color(0x1fffffff),
            height: 30,
            padding: EdgeInsets.symmetric(horizontal: 8),
            child: Center(
              child: Row(
                children: [
                  Expanded(
                      child: SizedBox(
                    width: double.infinity,
                    height: double.infinity,

                        child: TextField(
                      maxLines: 1,
                      // autofocus: true,
                      controller: _etController,
                      textAlignVertical: TextAlignVertical.center,
                      style: TextStyle(
                        fontSize: 14,
                        color: WColor.white,

                      ),
                      decoration: InputDecoration(
                        border: InputBorder.none,
                        hintText: "请输入关键字",
                        hintStyle: TextStyle(color: WColor.gray2, fontSize: 14),
                        hintMaxLines: 1,

                      ),
                      textInputAction: TextInputAction.search,
                      onChanged: (str) {
                        setState(() {
                          keyWords = str;
                        });
                      },
                      onSubmitted: (str) {
                        _refreshList();
                      },
                    ),
                  )),

                  if(keyWords.isNotEmpty) IconButton(
                    iconSize: 18,
                    alignment: Alignment.centerRight,
                    padding: EdgeInsets.all(0),
                    icon: Icon(
                      Icons.highlight_remove,
                      color: WColor.gray2,
                    ),
                    onPressed: () {
                      setState(() {
                        _etController.text = "";
                      });

                      keyWords = "";
                      _pageIndex = 0;
                    },
                  ) ,
                ],
              ),
            ),
          ),
        ),
        actions: [
          IconButton(
            icon: Icon(Icons.search),
            onPressed: () {
              _refreshList();
            },
          )
        ]);
  }

  /// 页面内容
  _contentPage(){
    if(keyWords.isEmpty) return _defaultPage();
    return _listPage();
  }

  /// 搜索结果列表
  _listPage(){
    return EasyRefresh(
      controller: _controller,
      enableControlFinishLoad: true,
      enableControlFinishRefresh: true,
      header: refreshHeader,
      footer: refreshFooter,
      firstRefresh: true,
      child: ListView.builder(
        itemBuilder: (BuildContext context, int index) {
          return ArticleItem(_articles[index], onRefresh: () {
            setState(() {
              List<Article> newList = [];
              newList.addAll(_articles);
              newList[index].collect = !(newList[index].collect ?? false);
              _articles = newList;
            });
          });
        },
        itemCount: _articles.length,
      ),
      onRefresh: () async {
        _refreshList();
      },
      onLoad: () async {
        _getArticles();
      },
    );
  }

  /// 默认页面，没输入关键词的页面
  _defaultPage() {
    var items = [
      "面试",
      "Studio3",
      "动画",
      "自定义View",
      "性能优化",
      "速度," "gradle",
      "Camera 相机",
      "代码混淆",
      "安全",
      "逆向",
      "加固",
    ];

    var child = items.map<Widget>((e) {
      return GestureDetector(
        onTap: () {
            setState(() {
              keyWords = e;
              _etController.text = keyWords;
            });
        },
        child: Container(
          padding: EdgeInsets.symmetric(vertical: 4, horizontal: 14),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(20)),
            color: wTheme.txItemBg,
          ),
          child: Text(
            e,
            style: TextStyle(fontSize: 13, color: wTheme.text1),
          ),
        ),
      );
    }).toList();


    return Container(
      color: wTheme.listItemBg,
      width: double.infinity,
      padding: EdgeInsets.only(left: 10, right: 10, top: 20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text("热门搜索", style: TextStyle(color: WColor.blue1, fontSize: 14),),

          Padding(padding: EdgeInsets.only(top: 10)),

          Wrap(
            spacing: 10,
            runSpacing: 10,
            children: child,
          )
        ],
      ),
    );
  }

  /// 重新请求列表
  _refreshList(){
    _pageIndex = 0;
    _articles.clear();
    _getArticles();
  }

  /// 获取文章列表
  _getArticles() async {

    ResultData result = await HttpManager.instance().post(
      "article/query/${_pageIndex}/json",
      params: {"k": keyWords},
      withLoading: false
    );

    _controller.finishRefresh();

    bind(_controller, result);

    if (result.success) {
      setState(() {
        if (_pageIndex == 0) {
          _articles = getArticleList(result.data["datas"]);
        } else {
          _articles.addAll(getArticleList(result.data["datas"]));
        }
      });
      _pageIndex++;
    } else {
      Fluttertoast.showToast(msg: result.msg);
    }
  }
}
